package com.cwd.arm.domain.entity;

import com.cwd.arm.common.util.BigDecimalUtil;
import lombok.Data;

import java.math.BigDecimal;

/**
* Description:确认收入
* Created on 2021年11月16日
* @author  yan
*/
@Data
public class ConfirmIncomeEntity {

    /**
    *
    */
    private Long id;

    /**
    * 项目id
    */
    private Long projectId;

    /**
    * 确认时间
    */
    private java.util.Date confirmDate;

    /**
    * 是否回执
    */
    private Boolean hasReceipt;

    /**
    * 累计百分比
    */
    private java.math.BigDecimal completionRate;

    /**
    * 确认收入
    */
    private java.math.BigDecimal confirmAmount;


    public void undo(){
        confirmAmount = BigDecimalUtil.minus(confirmAmount);
    }

    public void initAmount(ConfirmIncomeEntity oldConfirmIncomeEntity){
        if(oldConfirmIncomeEntity!=null){
            if(confirmAmount == null){
                confirmAmount = oldConfirmIncomeEntity.getConfirmAmount();
            }
        }
    }

    public boolean canAdd(BigDecimal contractAmount, BigDecimal projectConfirmAmount) {
        if (BigDecimalUtil.hasRecord(confirmAmount) && BigDecimalUtil.hasRecord(completionRate)) {
            return vailRateAmount(contractAmount, projectConfirmAmount, confirmAmount);
        }
        return true;
    }

    public boolean canUpdate(BigDecimal contractAmount, BigDecimal projectConfirmAmount, BigDecimal oldReceivableAmount) {
        if (BigDecimalUtil.hasRecord(confirmAmount) && BigDecimalUtil.hasRecord(completionRate)) {
            BigDecimal diffReceivableAmount = BigDecimalUtil.sub(confirmAmount, oldReceivableAmount);
            return vailRateAmount(contractAmount, projectConfirmAmount, diffReceivableAmount);
        }
        return true;
    }


    private boolean vailRateAmount(BigDecimal contractAmount, BigDecimal projectConfirmAmount, BigDecimal diffReceivableAmount) {
        BigDecimal rate = getRate(contractAmount, projectConfirmAmount, diffReceivableAmount);
        if (BigDecimalUtil.scaleRate(rate).compareTo(BigDecimalUtil.scaleRate(completionRate)) == 0) {
            return true;
        }
        return false;
    }

    private BigDecimal getRate(BigDecimal contractAmount, BigDecimal projectConfirmAmount, BigDecimal diffReceivableAmount) {
        BigDecimal newProjectReceivableAmount = BigDecimalUtil.add(projectConfirmAmount, diffReceivableAmount);
        return BigDecimalUtil.div2(newProjectReceivableAmount, contractAmount);
    }


}
